import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { protoActions } from 'reduxs'
import { getPostData, getFlagValue, showTeam, getTeamFlag, getPageFlag, getFileBlob, downloadBlod } from 'services/utils'
import { Dropdown, Menu, Icon, Button, message } from 'antd'
import DescriptionList from 'ant-design-pro/lib/DescriptionList'
import QueryTable from '../components/query-table'
import _ from 'lodash'
import Clipboard from 'react-clipboard.js'

const accessFlag = getPageFlag('/proto-data/daily-report', 'access')
const exportFlag = getPageFlag('/proto-data/daily-report', 'export')
const { Description } = DescriptionList
const MenuItem = Menu.Item
const tableHeads = ['当日总数据', 'PUSH数据', '灰度服数据', '去除PUSH、灰度服数据', '第三方渠道服数据']
const tableColumns = [
  {
    key: '1',
    title: '新增',
    dataIndex: 'data_0',
  },
  {
    key: '2',
    title: 'DAU',
    dataIndex: 'data_1',
  },
  {
    key: '3',
    title: '付费率',
    dataIndex: 'data_2',
  },
  {
    key: '4',
    title: '充值',
    dataIndex: 'data_3',
  },
  {
    key: '5',
    title: 'ARPU',
    dataIndex: 'data_4',
  },
  {
    key: '6',
    title: '次日留存',
    dataIndex: 'data_5',
  },
  {
    key: '7',
    title: '三日留存',
    dataIndex: 'data_6',
  },
  {
    key: '8',
    title: '七日留存',
    dataIndex: 'data_7',
  },
]

@connect(
  state => ({
    auth                : state.Passport.auth,
    parser              : state.Proto.parser,
    postData            : state.Proto.postData,
  }),
  dispatch => ({
    actions: bindActionCreators({ 
      ...protoActions
    }, dispatch)
  })
)
export default class DaliyReport extends PureComponent {

  state = {
    copyString: ''
  }

  constructor (props) {
    super(props)
    this.clipboardView = null
  }

  render () {
    const { location, parser, paths, auth, postData } = this.props
    const { PostOptions, BodyData } = getPostData(postData, 'daily-report')
    let options = {
      layoutOptions: {
        location,
        pageCode: accessFlag.value,
        breadcrumb: [
          { name: '主页', link: '/' },
          { name: '数据统计类' },
          { name: '每日统计' }
        ],
      },
      searchOptions: {
        begin: {
          name: '时间段',
          format: 'YYYY-MM-DD',
          required: { required: true, message: `请选择时间段!` },
          subtract: [6, 'days']
        },
      },
      proto: 'daily-report',
      tableHeads,
      tableColumns: [
        {
          key: '0',
          title: '#',
          dataIndex: 'data_head',
          width: 200
        },
        ...tableColumns
      ],
      tableScroll: {  },
      tablePagination: true,
      tableMode: 'listrow',
      tools: [
        <Dropdown overlay={(
            <Menu onClick={this.handleClickExport}>
              <MenuItem key="csv">csv文件</MenuItem>
              <MenuItem key="txt">txt文件</MenuItem>
              <MenuItem key="copy">粘贴板</MenuItem>
            </Menu>
          )}
          disabled={!BodyData || getFlagValue(auth, exportFlag.value, null)}
          >
          <Button style={{ marginLeft: 8 }} >
            导出数据 <Icon type="down" />
          </Button>
        </Dropdown>,
        <a id="download-blob-file"></a>,
        this.state.copyString !== '' && (
          <Clipboard 
            component="button" 
            className="ant-btn ant-btn-primary"
            style={{ marginLeft: 20 }} 
            ref={ view => this.clipboardView = view }
            data-clipboard-text={this.state.copyString} 
            onSuccess={this.handleSuccessCopy}
            //button-title="I'm a tooltip"
            >
            复制
          </Clipboard>
        )
      ],
      //remark: []

    }
    return (
      <QueryTable  {...options} />
    )
  }

  handleSuccessCopy = () => {
    this.setState({ copyString: '' })
    message.success('已经成功复制数据')
  }

  handleClickExport = ({ key }) => {
    const { postData } = this.props
    const { PostOptions, BodyData} = getPostData(postData, 'daily-report')
    if (!BodyData) return
    let dataTitle = _.map(tableColumns, 'title')
    if (key === 'csv') {
      let blodString = `\uFEFF${PostOptions['end']},${dataTitle.join(',')}\r\n`
      let n = 0
      for (let lineData of BodyData) {
        let lineInfo = filterLineData(`${tableHeads[n]};${lineData}`.split(';'))
        blodString += lineInfo
        blodString += '\r\n'
        n++
      }
      let fileBlob = getFileBlob(blodString, { type: 'text/cvs', encoding: 'utf-8' })
      downloadBlod(fileBlob, `daily-report.csv`)
    }
    else if (key === 'txt' || key === 'copy') {
      let blodString = ``
      let n = 0
      for (let lineData of BodyData) {
        let lineInfo = `${tableHeads[n]} -- ${PostOptions['end']}\r\n`
        let i = 0
        for (let item of dataTitle) {
          lineInfo += `${item}: ${lineData.split(';')[i] || '--'}\r\n`
          i++
        }
        blodString += `${lineInfo}\r\n`
        n++
      }
      if (key === 'txt') {
        let fileBlob = getFileBlob(blodString, { type: 'text/plain', encoding: 'utf-8' })
        downloadBlod(fileBlob, `daily-report.txt`)
      }
      if (key === 'copy') {
        this.setState({ copyString: blodString })
      }
    }
  }
}

const filterLineData = lineData => {
  let arr = []
  for (let e of lineData) {
    let info = e
    if (/\"/.test(e)) {
      info = info.replace(/\"/g, '\"\"')
    }
    arr.push(`"${info}\t"`)
  }
  return _.join(arr, ',')
}